/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reportcenter.report.support.query;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import reportcenter.report.dominio.param.ReportParam;

/**
 *
 * @author renan
 */
public class QueryInterceptor {

    private static final String STR_DEFAULT_STRING = "'string'";
    private static final String STR_DEFAULT_DATE = "'01/01/1901'";
    private static final String STR_DEFAULT_DECIMAL = "0";
    private static final String STR_DEFAULT_INTEGER = "69";
    private static final String STRING = "\\$S(.*?)\\}";
    private static final String DATE = "\\$D(.*?)\\}";
    private static final String DECIMAL = "\\$M(.*?)\\}";
    private static final String INTEGER = "\\$I(.*?)\\}";

    public List<ReportParam> searchParameters(String query) {
        List<ReportParam> params = new ArrayList<ReportParam>();

        //select col1, col2, col3 from table1 where col4 = {Informar o nome} and col5 = {Informe a data}

        Pattern p = Pattern.compile("\\$(.*?)\\}");
        Matcher m = p.matcher(query);

        int paramCount = 0;
        while (m.find()) {

            String found = m.group(1);
            String tipo = found.substring(0, 1);
            String answer = found.substring(2);

            if (tipo.equalsIgnoreCase("S")) {
                found = String.class.getName();
            } else if (tipo.equalsIgnoreCase("D")) {
                found = Date.class.getName();
            } else if (tipo.equalsIgnoreCase("M")) {
                found = BigDecimal.class.getName();
            } else if (tipo.equalsIgnoreCase("I")) {
                found = Integer.class.getName();
            }
            paramCount++;
            params.add(ReportParam.criarCom().paramAnswer(answer).paramName("param" + paramCount).paramClazz(found).create());
        }

        return params;
    }

    public String defaultParamValues(String str) {

        //STRING
        Pattern p = Pattern.compile(STRING);
        Matcher m = p.matcher(str);
        str = m.replaceAll(STR_DEFAULT_STRING);

        //DECIMAL
        p = Pattern.compile(DECIMAL);
        m = p.matcher(str);
        str = m.replaceAll(STR_DEFAULT_DECIMAL);

        //DATE
        p = Pattern.compile(DATE);
        m = p.matcher(str);
        str = m.replaceAll(STR_DEFAULT_DATE);

        //INTEGER
        p = Pattern.compile(INTEGER);
        m = p.matcher(str);
        str = m.replaceAll(STR_DEFAULT_INTEGER);

        return str;
    }
//    public String replaceOneByOne(String oldValue, String newValue){
//        StringBuilder builder = new StringBuilder(o);
//        builder.
//    }
//    public String transformToJasperParameters(String query){
//                
//        Pattern p = Pattern.compile("\\$(.*?)\\}");
//        Matcher m = p.matcher(query);
//
//        int paramCount=0;
//        StringBuilder builder = new StringBuilder(query);
//        while (m.find()) {
//            paramCount++;
//            query = query.replace(m.group(),"$P{param" + paramCount + "} ");
////            builder.append("$P{param" + paramCount + "}", builder.indexOf(m.group()), builder.indexOf(m.group()) + m.group().length()   );
////            System.out.println("Builder -> " + builder);
////            System.out.println(query.indexOf(m.group()));
//            
//        }
//        
//        return query;
//    }
    public String transformToJasperParameters(String query, Map parameters) {

        Pattern p = Pattern.compile("\\$(.*?)\\}");
        Matcher m = p.matcher(query);

        int paramCount = 0;
        StringBuilder builder = new StringBuilder(query);
        while (m.find()) {
            paramCount++;
            if (parameters.get("param" + paramCount).toString().contains(",")) {
                query = query.replace(m.group(), parameters.get("param" + paramCount).toString());
            } else {
                

                query = query.replace(m.group(), "$P{param" + paramCount + "} ");
//            builder.append("$P{param" + paramCount + "}", builder.indexOf(m.group()), builder.indexOf(m.group()) + m.group().length()   );
//            System.out.println("Builder -> " + builder);
//            System.out.println(query.indexOf(m.group()));
            }
        }

        return query;
    }
    //select * from tabela where str = $S{Informe a string} and codigo = $I{Informe og codigo} and codigooutro = $I{Informe o codigo}
    //select * from tabela where str =  where str = $S{Informe a string} and codigo = where str = $S{Informe a string} and codigo = $I{Informe og codigo} and codigooutro = 
//     public String transformToJasperParameters(String query){
//         
//         System.out.println("Query -> " + query);
//                
//        Pattern p = Pattern.compile("\\$(.*?)\\}");
//        Matcher m = p.matcher(query);
//
//        int paramCount=0;
//        int actualIndexEnd = 0;
//        StringBuilder builder = new StringBuilder();
//        while (m.find()) {
//            paramCount++;
//            
//            System.out.println(query.indexOf(m.group()));
//            query.substring(actualIndexEnd, query.indexOf(m.group()) );
//            
//            
//            builder.append(query.substring(actualIndexEnd, query.indexOf(m.group())));
//            builder.append("$P{param" + paramCount + "}");
//            
//            actualIndexEnd = (m.group().length() + query.indexOf(m.group()));
//        }
//        
//        return builder.toString();
//    }
//     
//     public void teste(String query){
////         System.out.println("First occurence -> " + );
//     }
    public static void main(String[] args) {//        System.out.println(new QueryInterceptor().transformToJasperParameters("select operacoes.data_operacao, operacoes.data_repasse, operacoes.codigo_loja, operacoes.tipo_operacao, operacoes.nome_cliente, operacoes.contrato,      operacoes.numero_cartao,       operacoes.nr_parcela,       operacoes.valor_bruto, (select nvl(sum(vr_rep), 0)          from verdecard.t416lafi " +
//         " where nr_ctr = operacoes.contrato and sg_fuc_hst = 'REPCMSEC') comissao, operacoes.valor_liquido from (select trunc(min(oper.dt_lan)) data_operacao, min(oper.dt_rep) data_repasse, oper.cd_loj codigo_loja, oper.nr_ctr contrato, oper.cd_car numero_cartao, oper.nm_por nome_cliente, max(ds_prd) tipo_operacao, (select sum(abs(vr_rep)) " +
//                  from verdecard.t416lafi
//                 where t416lafi.nr_ctr = oper.nr_ctr
//                   and nvl(t416lafi.ad_lib, 0) = nvl(oper.ad_lib, 0)
//                   and sg_fuc_hst not in
//                       ('REPVRTEFD', 'REPVRTEF', 'REPVRPOS', 'REPVRURA',
//                        'REPVRWEB', 'REPVRADM', 'REPVRTUC')) valor_bruto,
//               min(oper.nr_par) nr_parcela,
//               (select max(nr_par)
//                  from verdecard.t416lafi
//                 where t416lafi.nr_ctr = oper.nr_ctr
//                   and nvl(t416lafi.ad_lib, 0) = nvl(oper.ad_lib, 0)) 
//qt_parcelas,
//               (sum(oper.vr_par)) valor_parcelas,
//               sum(oper.vr_adm) valor_administrador,
//               sum(oper.vr_tuc) valor_tuc,
//               sum(oper.vr_meio) valor_meio_captura,
//               (sum(oper.vr_par) +
//               (sum(oper.vr_adm) + sum(oper.vr_tuc) + 
//sum(oper.vr_meio))) valor_liquido
//          from (select lafi.nr_ctr,
//                       lafi.ad_lib,
//                       lafi.nr_par,
//                       lafi.dt_lan,
//                       lafi.dt_rep,
//                       case when lafi.sg_fuc_hst = 'REPVRCOMCS'
//                            then case when (select max(lafi1.cd_loj) 
//from verdecard.t416lafi lafi1
//                                  where lafi1.nr_ctr = lafi.nr_ctr
//                                    and lafi1.ad_lib = lafi.ad_lib
//                                    and lafi1.sg_fuc_hst = 'REPVRCARN'
//                                    and ((select to_date(abe.dt_abe) 
//from verdecard.estabel abe
//                                          where abe.cd_loj = 
//lafi1.cd_loj) <= sysdate)
//                                  )is null then lafi.cd_loj else
//                                      (select max(lafi1.cd_loj) from 
//verdecard.t416lafi lafi1
//                                       where lafi1.nr_ctr = lafi.nr_ctr
//                                         and lafi1.ad_lib = lafi.ad_lib
//                                         and lafi1.sg_fuc_hst = 'REPVRCARN'
//                                         and ((select 
//to_date(abe.dt_abe) from verdecard.estabel abe
//                                               where abe.cd_loj = 
//lafi1.cd_loj) <= sysdate)) end
//                            else lafi.cd_loj end cd_loj,
//                       cart.cd_car,
//                       cart.nm_por,
//                       (case
//                         when lafi.sg_fuc_hst = 'REPVRCOMCC' then
//                          (select ds_prd from autorizador.t411prod where 
//sg_prd = 'CC')
//                         when lafi.sg_fuc_hst = 'REPVRCOMCD' then
//                          (select ds_prd from autorizador.t411prod where 
//sg_prd = 'CD')
//                         when lafi.sg_fuc_hst = 'REPVRCOMCI' then
//                          (select ds_prd from autorizador.t411prod where 
//sg_prd = 'CI')
//                         when lafi.sg_fuc_hst = 'REPVRCOMCL' then
//                          (select ds_prd from autorizador.t411prod where 
//sg_prd = 'CL')
//                         when lafi.sg_fuc_hst = 'REPVRCOMCJ' then
//                          (select ds_prd from autorizador.t411prod where 
//sg_prd = 'CJ')
//                         when lafi.sg_fuc_hst = 'REPVRCOMCS' then
//                          (select ds_prd from autorizador.t411prod where 
//sg_prd = 'CS')
//                         when lafi.sg_fuc_hst = 'COMPREPAGO' then
//                          (select ds_prd from autorizador.t411prod where 
//sg_prd = 'PP')
//                         else
//                          ''
//                       end) ds_prd,
//                       nvl((case
//                             when lafi.sg_fuc_hst in
//                                  ('REPVRCOMCC', 'REPVRCOMCD', 'REPVRCOMCI',
//                                   'REPVRCOMCL', 'REPVRCOMCJ', 'REPVRCOMCS',
//                                   'COMPREPAGO') then
//                              vr_rep
//                           end),
//                           0) vr_par,
//                       nvl((case
//                             when lafi.sg_fuc_hst in ('REPVRTUC') then
//                              vr_rep
//                           end),
//                           0) vr_tuc,
//                       nvl((case
//                             when lafi.sg_fuc_hst in ('REPVRADM') then
//                              vr_rep
//                           end),
//                           0) vr_adm,
//                       nvl((case
//                             when lafi.sg_fuc_hst in
//                                  ('REPVRTEFD', 'REPVRTEF', 'REPVRPOS', 
//'REPVRURA',
//                                   'REPVRWEB') then
//                              vr_rep
//                           end),
//                           0) vr_meio
//                  from verdecard.t416lafi lafi
//                  left outer join verdecard.t416copa copa on 
//(copa.nr_ctr = lafi.nr_ctr)
//                  left outer join autorizador.t411cart cart on 
//(cart.cd_car = copa.cd_car)
//                 where
//                       trunc(lafi.dt_rep) = to_date(&data_repasse, 
//'DD/MM/YYYY')-- preencher a data inicial (formato= 'DD/MM/AAAA')
//                   --and trunc(lafi.dt_lan) <= to_date(&data_final, 
//'DD/MM/YYYY') -- preencher a data final (formato= 'DD/MM/AAAA')
//                   and lafi.sg_fuc_hst in ('REPVRCOMCC',
//                                           'REPVRCOMCD',
//                                           'REPVRCOMCI',
//                                           'REPVRCOMCL',
//                                           'REPVRCOMCJ',
//                                           'REPVRCOMCS',
//                                           'COMPREPAGO',
//                                           'REPVRTEFD',
//                                           'REPVRTEF',
//                                           'REPVRPOS',
//                                           'REPVRURA',
//                                           'REPVRWEB',
//                                           'REPVRTUC',
//                                           'REPVRADM')
//                   and lafi.cd_loj in (&cd_loja,1) -- preencher o codigo 
//do estabelecimento
//                   and (lafi.cd_loj in
//                        (select t411loja.cd_loj
//                           from autorizador.t411loja
//                          where t411loja.cd_lji = &cd_convenio -- 
//preencher o codigo do convenio
//                            and t411loja.id_apu_idp = 'N') or
//                        (lafi.cd_loj is null and lafi.cd_lji = 
//&cd_convenio -- preencher o codigo do convenio
//                        ))) oper
//         group by oper.nr_ctr,
//                  oper.ad_lib,
//                  oper.cd_loj,
//                  oper.cd_car,
//                  oper.nm_por,
//                  oper.nr_par
//         order by 2, oper.nr_ctr, oper.ad_lib, oper.nr_par) operacoes
// where tipo_operacao is not null
//   and operacoes.codigo_loja = &cd_loja"));
//        new QueryInterceptor().teste("select * from tabela where str = $S{Informe a string} and codigo = $I{Informe og codigo} and codigooutro = $I{Informe o codigo}");
    }
}
